package com.ljx.blog.article.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljx.blog.article.domain.entity.Article;
import com.ljx.blog.article.domain.vo.req.ArticlePageReq;
import com.ljx.blog.article.domain.vo.req.ArticleSubmitCheckReq;
import com.ljx.blog.article.domain.vo.req.ArticleSubmitReq;
import com.ljx.blog.article.domain.vo.resp.ArticleResp;
import com.ljx.blog.article.mapper.ArticleMapper;
import com.ljx.blog.article.service.ArticleService;
import com.ljx.blog.common.domain.vo.resp.PageResp;
import com.ljx.blog.common.enums.CommonStatusTypeEnum;
import com.ljx.blog.common.exception.ApiException;
import com.ljx.blog.security.util.UserUtil;
import com.ljx.blog.user.domain.dto.UserFlagDto;
import com.ljx.blog.user.domain.vo.resp.UserResp;
import com.ljx.blog.user.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-10-12  21:24
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private UserService userService;

    @Override
    public ArticleResp getInfo(Long articleId) {
        Article article = articleMapper.selectById(articleId);
        if (article.getStatus().equals(CommonStatusTypeEnum.BAN.getKey())){
            throw new ApiException("文章已经删除");
        }
        UserResp userResp = userService.getInfo(article.getUid());
        ArticleResp articleResp = BeanUtil.copyProperties(article, ArticleResp.class);
        articleResp.setName(userResp.getName());

        return articleResp;
    }

    @Override
    public PageResp<ArticleResp> getPage(ArticlePageReq req) {
        PageResp<Article> articlePage = getArticlePage(req);

        return PageResp.<ArticleResp>builder()
                .total(articlePage.getTotal())
                .list(BeanUtil.copyToList(articlePage.getList(), ArticleResp.class))
                .build();
    }

    private PageResp<Article> getArticlePage(ArticlePageReq req){
        List<Article> lists = articleMapper.getPage(req, req.getPageSize() * (req.getCurrPage() - 1), UserUtil.tryToGetTenantId());
        LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(req.getUserId())){
            lambdaQueryWrapper.eq(Article::getUid, req.getUserId());
            if (Objects.nonNull(req.getStatus())){
                lambdaQueryWrapper.eq(Article::getStatus, req.getStatus());
            }
        }
        if (Objects.isNull(req.getStatus())){
            lambdaQueryWrapper.eq(Article::getStatus, CommonStatusTypeEnum.NORMAL.getKey());
        }
        if (Objects.nonNull(req.getType())){
            lambdaQueryWrapper.eq(Article::getType, req.getType());
        }
        if (Objects.nonNull(req.getKey())){
            lambdaQueryWrapper.like(Article::getTitle, req.getKey());
        }
        if (Objects.nonNull(req.getCategoryId())){
            lambdaQueryWrapper.eq(Article::getCategoryId, req.getCategoryId());
        }
        Long total = Long.valueOf(articleMapper.selectCount(lambdaQueryWrapper));

        return PageResp.<Article>builder()
                .total(total)
                .list(lists)
                .build();
    }

    @Override
    public PageResp<Article> getPageByAdmin(ArticlePageReq req) {
        req.setUserFlagDto(new UserFlagDto(UserUtil.checkIsTenantAdmin(), UserUtil.checkIsPlatform()));
        return getArticlePage(req);
    }

    @Override
    @Transactional
    public ArticleResp submit(ArticleSubmitReq req) {
        UserUtil.checkIsSameTenant();
        Article article;
        if (Objects.isNull(req.getId())){
            checkSubmitParams(req);
            article = BeanUtil.copyProperties(req, Article.class);
            article.setUid(UserUtil.getUserId());
            articleMapper.insert(article);
        } else {
            article = articleMapper.selectById(req.getId());
            if (!article.getUid().equals(UserUtil.getUserId())){
                throw new ApiException("非法操作");
            }
            BeanUtils.copyProperties(req, article);
            articleMapper.updateById(article);
        }
        return article.getStatus().equals(CommonStatusTypeEnum.NORMAL.getKey()) ? getInfo(article.getId()) : new ArticleResp();
    }

    private void checkSubmitParams(ArticleSubmitReq req) {
        if (StrUtil.isEmpty(req.getTitle())){
            throw new ApiException("标题不能为空");
        }
        if (StrUtil.isEmpty(req.getContent())){
            throw new ApiException("内容不能为空");
        }
        if (StrUtil.isEmpty(req.getSource())){
            throw new ApiException("来源不能为空");
        }
        if (Objects.isNull(req.getCategoryId())){
            throw new ApiException("分类不能为空");
        }
        if (Objects.isNull(req.getTags())){
            throw new ApiException("标签能为空");
        }
        if (Objects.isNull(req.getType())){
            throw new ApiException("类型能为空");
        }
    }

    @Override
    public Boolean submitCheck(ArticleSubmitCheckReq req) {
        return UserUtil.tryToGetTenantId().equals(UserUtil.tryToGetUserTenantId(UserUtil.getUserId()))
                && (Objects.isNull(req.getArticleId())
                || articleMapper.selectById(req.getArticleId()).getUid().equals(UserUtil.getUserId()));
    }
}
